<template>
  <div>
    <el-row :gutter="20">
      <splitpanes class="default-theme">
        <!--文件数据-->
        <pane size="16">
          <div>
            <el-scrollbar height="82vh">
              <el-col>
                <div class="head-container">
                  <el-input
                    v-model="deptName"
                    clearable
                    placeholder="请输入文件名"
                    prefix-icon="Search"
                    style="margin-bottom: 20px"
                  />
                </div>
                <div>
                  <el-tree
                    ref="deptTreeRef"
                    :data="treeDataWithTop"
                    :props="defaultProps"
                    :filter-node-method="filterNode"
                    node-key="root"
                    default-expand-all
                    :highlight-current="true"
                    @node-click="handleNodeClick"
                  />
                </div>
              </el-col>
            </el-scrollbar>
          </div>
        </pane>
        <pane size="84">
          <el-col>
            <el-card>
              <el-alert
                type="warning"
                :closable="false"
                style="margin-bottom: 10px; font-size: 12px"
              >
                <span>{{ `当前目录：${searchName}` }}</span>
                <div style="font-size: 13px">
                  <el-icon><WarningFilled /></el-icon>只能上传ftl文件
                </div>
              </el-alert>
              <el-form
                ref="ruleFormRef"
                style="max-width: 800px"
                :model="ruleForm"
                :rules="rules"
                :inline="true"
                class="demo-ruleForm"
                status-icon
                @submit.prevent
                v-if="isCreateRole"
              >
                <el-form-item>
                  <el-button type="success" @click="onCreateModel">
                    创建模板
                  </el-button>
                </el-form-item>
                <el-form-item label="新建目录" prop="menu">
                  <el-input v-model="ruleForm.menu" clearable />
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    size="small"
                    @click="submitForm(ruleFormRef)"
                  >
                    新 建
                  </el-button>
                  <el-button size="small" @click="ruleFormRef.resetFields()">
                    重 置
                  </el-button>
                </el-form-item>
              </el-form>
              <!-- 表格部分 -->
              <div style="margin-bottom: 5px">
                <el-button
                  type="danger"
                  plain
                  size="small"
                  :disabled="multiple"
                  @click="onDeleteMultiple"
                  v-if="isDeleteRole"
                  ><el-icon><DeleteFilled /></el-icon>删除</el-button
                >
              </div>
              <el-table
                :data="tableData"
                @selection-change="handleSelectionChange"
                style="width: 100%"
                v-loading="loading"
              >
                <el-table-column
                  type="selection"
                  :selectable="selectable"
                  width="50"
                />
                <el-table-column prop="filename" label="文件名" />
                <el-table-column prop="size" label="大小">
                  <template #default="{ row }">
                    <span>{{ `${row.size} KB` }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="lastModified"
                  label="最后修改时间"
                  sortable
                  :sort-orders="['descending', 'ascending']"
                >
                  <template #default="{ row }">
                    <span>{{
                      dayjs(row.lastModified).format('YYYY-MM-DD HH:mm:ss')
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template #default="{ row }">
                    <el-button
                      link
                      plain
                      type="primary"
                      size="small"
                      @click="onRename(row)"
                      ><el-icon><View /></el-icon>重命名</el-button
                    >
                    <el-button
                      link
                      plain
                      type="primary"
                      size="small"
                      @click="onEdit(row)"
                      :disabled="row.directory"
                      v-if="isUpdateRole"
                      ><el-icon><Edit /></el-icon>修改</el-button
                    >
                    <el-button
                      link
                      plain
                      type="primary"
                      size="small"
                      @click="onDelete(row)"
                      v-if="isDeleteRole"
                      ><el-icon><Delete /></el-icon>删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <!-- 分页器 -->
              <pagination
                v-show="total > 0"
                :total="total"
                v-model:page="queryParams.pageNo"
                v-model:limit="queryParams.pageSize"
                @pagination="getList(searchName)"
              />
            </el-card>
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
    <!-- 添加删除弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="40%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="resetCreateForm(createRuleFormRef)"
    >
      <el-form
        ref="createRuleFormRef"
        style="max-width: 600px"
        :model="createRuleForm"
        :rules="createRules"
        class="demo-ruleForm"
        status-icon
        @submit.prevent
      >
        <el-form-item label="文件名" prop="fileName">
          <el-input
            v-model="createRuleForm.fileName"
            style="width: 220px"
            :disabled="title !== '创建模板'"
          /><span v-if="title === '创建模板'">.ftl</span>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="createRuleForm.source"
            type="textarea"
            style="height: 220px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetCreateForm(createRuleFormRef)"
            >重 置</el-button
          >
          <el-button
            type="primary"
            @click="submitCreateForm(createRuleFormRef)"
          >
            提 交
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 重命名弹窗 -->
    <el-dialog
      v-model="renameDialogVisible"
      :title="renameTitle"
      width="40%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="renameRuleFormRef"
        style="max-width: 600px"
        :model="renameRuleForm"
        :rules="renameRules"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="原名称">
          <el-input
            v-model="renameRuleForm.filename"
            :disabled="true"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="新名称" prop="newFileName">
          <el-input v-model="renameRuleForm.newFileName" style="width: 220px" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="renameResetCreateForm(renameRuleFormRef)"
            >重 置</el-button
          >
          <el-button
            type="primary"
            @click="renameSubmitCreateForm(renameRuleFormRef)"
          >
            提 交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, watch, onMounted } from 'vue'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import { dayjs, ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from 'vuex'
import {
  getTemplateList,
  getTemplateTreeList,
  crateDir,
  delDirSingle,
  delDirMultiple,
  createModel,
  updateModel,
  reName
} from '@/api/template/modelList.js'

const store = useStore()
const buttonRole = store.state.app.buttonRole
const userId = store.state.app.user.id
const deptName = ref('')
const selectable = (row) => ![1, 2].includes(row.id)
const deptTreeRef = ref()
const ruleFormRef = ref()
const createRuleFormRef = ref()
const renameRuleFormRef = ref()
const dialogVisible = ref(false)
const searchName = ref('static_resource/model')
const renameDialogVisible = ref(false)
const title = ref('')
const renameTitle = ref('')
const multiple = ref(true)
const renameSource = ref('')
const loading = ref(true)
const total = ref(0)
const ids = []
const treeData = ref([])
const tableData = ref([])
const treeDataWithTop = ref([])

// 按钮权限
const isDeleteRole = ref(true)
const isCreateRole = ref(true)
const isUpdateRole = ref(true)
const ruleForm = ref({
  menu: ''
})
const renameRuleForm = ref({
  filename: '',
  name: '',
  newFileName: '',
  path: ''
})
const queryParams = ref({
  pageNo: 1,
  pageSize: 10
})
const createRuleForm = ref({
  fileName: '',
  source: ''
})
const rules = reactive({
  menu: [{ required: true, message: '请输入目录名', trigger: 'blur' }]
})
const createRules = reactive({
  fileName: [{ required: true, message: '请输入文件名', trigger: 'blur' }]
})
const renameRules = reactive({
  newFileName: [
    { required: true, message: '请输入新的文件名', trigger: 'blur' }
  ]
})
const defaultProps = {
  children: 'children',
  label: 'filename'
}

onMounted(() => {
  getTreeList()
  getList(searchName.value)
})

// 结构树搜索
watch(deptName, (val) => {
  deptTreeRef.value.filter(val)
})

// 模板根目录
const addTopNode = (treeData) => {
  return [
    {
      root: '/static_resource/model',
      filename: '模板根目录',
      children: treeData
    }
  ]
}

// 树形数据
const getTreeList = async () => {
  await getTemplateTreeList()
    .then((res) => {
      treeData.value = res.data.tplList
      treeDataWithTop.value = addTopNode(res.data.tplList)
      loading.value = false
    })
    .catch((err) => {
      console.log(err)
      loading.value = false
    })
}

// 表格数据
const getList = async (root) => {
  // 按钮权限
  console.log(buttonRole)
  buttonRole.map((item) => {
    if ('模板管理'.includes(item.name)) {
      console.log(item)
      item.children.map((list) => {
        if (list.name === '模板添加') {
          console.log(list)
          if (list.isbutton) {
            isCreateRole.value = true
          } else {
            isCreateRole.value = false
          }
        }
        if (list.name === '模板修改') {
          if (list.isbutton) {
            isUpdateRole.value = true
          } else {
            isUpdateRole.value = false
          }
        }
        if (list.name === '模板删除') {
          if (list.isbutton) {
            isDeleteRole.value = true
          } else {
            isDeleteRole.value = false
          }
        }
      })
    }
  })
  loading.value = true
  await getTemplateList({
    root: root,
    rel: '/',
    pageNo: queryParams.value.pageNo,
    pageSize: queryParams.value.pageSize
  })
    .then((res) => {
      loading.value = false
      tableData.value = res.data.list
      total.value = res.data.total
    })
    .catch((err) => {
      console.log(err)
      loading.value = false
    })
}

const onCreateModel = () => {
  title.value = '创建模板'
  createRuleForm.value = {
    fileName: '',
    source: ''
  }
  dialogVisible.value = true
}
// 新建目录
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const res = await crateDir({
        root: searchName.value,
        dirName: ruleForm.value.menu
      })
      ruleForm.value.menu = ''
      ElMessage({
        type: 'success',
        message: res.data.message
      })
      await getList(searchName.value)
      await getTreeList()
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 弹窗提交
const submitCreateForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (title.value === '创建模板') {
        await createModel({
          root: searchName.value,
          filename: createRuleForm.value.fileName,
          source: createRuleForm.value.source,
          userId
        })
          .then(async (res) => {
            dialogVisible.value = false
            ElMessage({
              type: 'success',
              message: res.message
            })
            await getList(searchName.value)
            await getTreeList()
          })
          .catch((err) => {
            console.log(err)
          })
      }
      if (title.value === '修改模板') {
        await updateModel({
          root: `/${searchName.value}`,
          filename: `/${searchName.value}/${createRuleForm.value.fileName}`,
          source: createRuleForm.value.source,
          userId
        })
          .then(async (res) => {
            dialogVisible.value = false
            ElMessage({
              type: 'success',
              message: res.message
            })
            await getList(searchName.value)
            await getTreeList()
          })
          .catch((err) => {
            console.log(err)
          })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 修改
const onEdit = (row) => {
  title.value = '修改模板'
  dialogVisible.value = true
  createRuleForm.value.fileName = row.filename
  createRuleForm.value.source = row.source
  renameSource.value = row.source
}

// 创建修改弹窗重置
const resetCreateForm = (formEl) => {
  if (title.value === '修改模板') {
    createRuleForm.value = {
      fileName: createRuleForm.value.fileName,
      source: renameSource.value
    }
  } else {
    createRuleForm.value = {
      fileName: '',
      source: ''
    }
  }

  formEl.resetFields()
}

// 重命名
const onRename = (row) => {
  renameTitle.value = '重命名'
  renameDialogVisible.value = true
  renameRuleForm.value.filename = row.filename
  renameRuleForm.value.name = row.name
  renameRuleForm.value.newFileName = row.filename
  renameRuleForm.value.path = row.path
}
// 重命名弹窗提交
const renameSubmitCreateForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      renameDialogVisible.value = false
      console.log('submit!')
      reName({
        root: renameRuleForm.value.path,
        origName: renameRuleForm.value.name,
        distName: `${renameRuleForm.value.path}/${renameRuleForm.value.newFileName}`
      }).then((res) => {
        ElMessage({
          type: 'success',
          message: res.data.message
        })
        getList(searchName.value)
        getTreeList()
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 重命名弹窗重置
const renameResetCreateForm = (formEl) => {
  formEl.resetFields()
  renameRuleForm.value.newFileName = renameRuleForm.value.filename
}

// 删除
const onDelete = (row) => {
  ElMessageBox.confirm('您确定要删除这条数据吗？', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await delDirSingle({
        root: searchName.value,
        name: row.name,
        rel: '/',
        userId
      })
      ElMessage({
        type: 'success',
        message: res.message
      })
      await getList(searchName.value)
      await getTreeList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
// 删除多个
const onDeleteMultiple = () => {
  ElMessageBox.confirm('您确定要删除这些数据吗？', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 创建 URLSearchParams 实例
      const params = new URLSearchParams()
      // 添加固定参数
      params.append('root', '/static_resource/model')
      ids.value.forEach((name) => {
        params.append('name', name)
      })
      params.append('rel', '/')
      params.append('userId', userId)
      const res = await delDirMultiple(params)
      ElMessage({
        type: 'success',
        message: res.message
      })
      await getList(searchName.value)
      await getTreeList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.name)
  multiple.value = !selection.length
}
const filterNode = (value, data) => {
  if (!value) return true
  return data.filename.includes(value)
}
const handleNodeClick = (data) => {
  // 使用正则表达式匹配WEB-INF及其后面的路径
  const match = data.root.match(/(static_resource.*)/)
  if (match) {
    const webInfPath = match[1]
    // 替换反斜杠为正斜杠
    const formattedPath = webInfPath.replace(/\\/g, '/')
    searchName.value = formattedPath
    getList(searchName.value)
  } else {
    console.log('未找到路径')
  }
}
</script>

<style lang="scss" scoped>
.splitpanes {
  .splitpanes__pane {
    background-color: #fff;
  }
  .splitpanes__splitter {
    width: 7px !important;
    border-left: 1px solid #eee;
    background-color: #1d1e1f;
    border-color: #303030;

    &:hover {
      background-color: #2d2d2d;
    }

    &:before,
    &:after {
      background-color: #303030;
    }
  }
}
.head-container {
  position: sticky;
  top: 0;
  z-index: 100;
}
:deep(.el-table .el-table__header-wrapper th) {
  word-break: break-word;
  background-color: #f8f8f9 !important;
  color: #515a6e;
  height: 40px !important;
  font-size: 13px;
}
:deep(.el-form-item__label) {
  font-weight: bold;
}
:deep(.el-textarea__inner) {
  height: 230px;
}
</style>
